import React, {useEffect, useState, memo} from 'react'

import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import BatchUpload from '../list/components/BatchUpload'

import {
	getTableList,
	importSave,
	getErrorList,
} from '@/service/carMessage/maintenance'
import {getAllCitys, getCompany} from '@/service/common/index'
import {translateDataToTree} from '@/utils/common/index'
import 'moment/locale/zh-cn'

import {maintenanceType, operationType, workOrderType} from './enum'
import {modalApi} from '@/utils/modalReq'

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

const targetDom = memo((props: {user: {orgId: string | number}}) => {
	const {orgId} = props.user
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)

	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)

	const [fileObj, setFileObj] = useState<any>()
	// 城市
	const [citysList, setCitysList] = useState<CityOption[]>([])

	const [tableList, setTableList] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [orgList, setOrgList] = useState([])

	// 初始化-城市
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
	}

	// 初始化-需求组织数据
	const getCompanyFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setOrgList(() => list as any)
			}
		})
	}

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setTableList(() => res.data.records)
					setTotal(res.data.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	useEffect(() => {
		getCitysFun()
	}, [])

	useEffect(() => {
		getCompanyFun()
	}, [orgId])

	useEffect(() => {
		onListFun()
	}, [params])

	// 列表
	const columns: ColumnsType<TargetAPI.TargetColumns> = [
		{
			title: '工单ID',
			dataIndex: 'workOrderId',
			align: 'center',
			width: 100,
		},
		{
			title: '工单类型',
			dataIndex: 'workOrderType',
			align: 'center',
			width: 200,
			render: (text) => workOrderType[text],
		},
		{
			title: '维保时间',
			dataIndex: 'maintenanceTime',
			align: 'center',
			width: 200,
			render: (text) => (
				<div>
					{text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '--'}
				</div>
			),
		},
		{
			title: '车辆ID',
			dataIndex: 'carId',
			align: 'center',
			width: 140,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '持有方',
			dataIndex: 'assertsOwnerName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '所有人',
			dataIndex: 'ownerName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '运营分类',
			dataIndex: 'operationType',
			align: 'center',
			width: 150,
			render: (text) => operationType[text],
		},
		{
			title: '资产所有方',
			dataIndex: 'assertsOwnerName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '司机姓名',
			dataIndex: 'driverName',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '联系电话',
			dataIndex: 'driverMobile',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '身份证号',
			dataIndex: 'driverCardNo',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '本次里程',
			dataIndex: 'thisDistance',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '维保业务类型',
			dataIndex: 'maintenanceType',
			align: 'center',
			width: 150,
			render: (text) => maintenanceType[text],
		},
		{
			title: '维保店',
			dataIndex: 'maintenanceShop',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '维保店城市',
			dataIndex: 'maintenanceCity',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '送修人',
			dataIndex: 'repairPerson',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '送修人电话',
			dataIndex: 'repairMobile',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record) => (
				<div>
					<Button
						type="link"
						size="small"
						onClick={() => {
							history.push({
								pathname: '/carMessage/maintenance/details',
								query: {
									id: record.id,
								},
							})
						}}>
						查看
					</Button>
				</div>
			),
		},
	]

	// 搜素
	const onFinish = (values: any) => {
		const value = values
		if (value?.maintenanceStartAndEndTime) {
			value.maintenanceStartAndEndTime = `${moment(
				value.maintenanceStartAndEndTime[0],
			).format('YYYY-MM-DD')}~${moment(
				value.maintenanceStartAndEndTime[1],
			).format('YYYY-MM-DD')}`
		}
		const param = {
			current: 1,
			size: 10,
		}
		setSearchData(value)
		setParams(param)
	}

	// 搜索重置
	const onReset = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setSearchData({})
		setParams(param)
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'workOrderId',
						name: 'workOrderId',
						label: '工单ID',
					},
					{
						type: 'input',
						key: 'carId',
						name: 'carId',
						label: '车辆ID',
						rules: [
							{
								pattern: /^[0-9]*$/,
								message: '车辆ID请输入数字',
							},
						],
					},
					{
						type: 'input',
						label: '车牌号',
						name: 'carPlateNo',
						key: 'carPlateNo',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'select',
						key: 'operationType',
						name: 'operationType',
						label: '运营分类',
						title: 'text',
						items: Object.keys(operationType).map(
							(item: string) => ({
								value: item,
								text: operationType[item],
							}),
						),
					},
					{
						type: 'treeSelect',
						label: '资产所有方',
						name: 'assertsOwnerId',
						key: 'assertsOwnerId',
						keys: 'id',
						title: 'name',
						treeData: [...orgList],
					},
					{
						type: 'input',
						label: '维保店',
						name: 'maintenanceShop',
						key: 'maintenanceShop',
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'select',
						key: 'maintenanceType',
						name: 'maintenanceType',
						label: '维保业务类型',
						title: 'text',
						items: Object.keys(maintenanceType).map(
							(item: string) => ({
								value: item,
								text: maintenanceType[item],
							}),
						),
					},
					{
						type: 'input',
						label: '送修人',
						name: 'repairPerson',
						key: 'repairPerson',
					},
					{
						type: 'input',
						label: '送修电话',
						name: 'repairMobile',
						key: 'repairMobile',
					},
				],
			},
			{
				type: 'group',
				key: 'group4',
				groupItems: [
					{
						type: 'select',
						key: 'workOrderType',
						name: 'workOrderType',
						label: '工单类型 ',
						title: 'text',
						items: Object.keys(workOrderType).map(
							(item: string) => ({
								value: item,
								text: workOrderType[item],
							}),
						),
					},
					{
						type: 'dateRange',
						label: '维保时间',
						name: 'maintenanceStartAndEndTime',
						key: 'maintenanceStartAndEndTime',
					},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [citysList, orgList])

	const batchColumns: any = [
		{
			title: '工单类型',
			dataIndex: 'workOrderType',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车架号',
			dataIndex: 'vin',
			align: 'center',
			width: 140,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '申请时间',
			dataIndex: 'applyTime',
			align: 'center',
			width: 250,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '维修类型',
			dataIndex: 'maintenanceType',
			align: 'center',
			width: 150,
			render: (text: string) => <>{maintenanceType[text]}</>,
		},
		{
			title: '实际数量',
			dataIndex: 'actualNum',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '记账公司',
			dataIndex: 'bookKeeping',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '总价',
			dataIndex: 'workOrderId',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '工单id',
			dataIndex: 'licenseEndTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '协议金额',
			dataIndex: 'actualAmount',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},

		{
			title: '错误信息',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
			fixed: 'right',
			render: (text: string) => <span>{text || '--'}</span>,
		},
	]

	const importData = () => {
		const formdata = new FormData()
		formdata.append('type', '2')
		formdata.append('excel', fileObj)

		importSave(formdata)
			.then((res: any) => {
				if (res?.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((error: any) => {
				message.error(error)
			})
		setIsUploadModalOpen(() => false)
	}

	// 获取导入失败表格数据
	const onTableList = (data: any) =>
		getErrorList({...data}).then((res: any) => {
			if (res?.success) {
				return res
			}
			return []
		})

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					{/* <Button
              type="primary"
              ghost
              size="small"
              onClick={() => {
                setModalTitle(() => '新增指标');
                setIsModalOpen(() => true);
              }}
            >
              新增
            </Button> */}
					<Button
						type="primary"
						ghost
						size="small"
						onClick={() => setIsUploadModalOpen(true)}>
						批量导入
					</Button>
					{/* <Button ghost size="small" className="btn_warning">
              导出
            </Button> */}
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
			</div>
			{/* <Modal
					title={modalTitle}
					open={isModalOpen}
					onOk={onSubmit}
					onCancel={onCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button onClick={onCancel}>取消</Button>
							<Button
								type="primary"
								size="small"
								onClick={onSubmit}>
								保存
							</Button>
						</>
					}>
					<Form
						form={form}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '100px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off">
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="指标编号"
									name="licenseNo"
									rules={[{required: true}]}>
									<Input placeholder="请输入" disabled />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="所属公司"
									name="companyId"
									rules={[{required: true}]}>
									<TreeSelect
										showSearch
										style={{width: '100%'}}
										dropdownStyle={{
											maxHeight: 400,
											overflow: 'auto',
										}}
										placeholder="请选择"
										allowClear
										treeDefaultExpandAll
										fieldNames={{
											label: 'name',
											value: 'id',
										}}
										treeDataSimpleMode
										treeData={companyData}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item label="注册城市" name="cityId">
									<Cascader
										fieldNames={{
											label: 'name',
											value: 'id',
											children: 'cityInfoList',
										}}
										options={citysList}
										placeholder="请选择"
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="所有人"
									name="ownerName"
									rules={[{required: true}]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="持有方"
									name="holderId"
									rules={[{required: true}]}>
									<Select
										placeholder="请选择"
										fieldNames={{
											value: 'value',
											label: 'valueName',
										}}
										options={[...holderDict]}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="车牌性质"
									name="licenseProperty"
									rules={[{required: true}]}>
									<Select
										placeholder="请选择"
										fieldNames={{
											value: 'key',
											label: 'label',
										}}
										options={[...licenseProperty]}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="车牌状态"
									name="status"
									rules={[{required: true}]}>
									<Select
										placeholder="请选择"
										fieldNames={{
											value: 'key',
											label: 'label',
										}}
										options={[...carLicenseStatus]}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="车牌号"
									name="carPlateNo"
									rules={[{required: true}]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label=" 指标日期"
									name="licenseTime"
									rules={[{required: true}]}>
									<DatePicker.RangePicker
										allowClear
										format="YYYY-MM-DD"
										style={{width: '100%'}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Modal> */}
			{/* <Modal
					title={batchModalTitle}
					open={isBatchModalOpen}
					onOk={onBatchSubmit}
					onCancel={onBatchCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button onClick={onBatchCancel}>取消</Button>
							<Button
								type="primary"
								size="small"
								onClick={onBatchSubmit}>
								保存
							</Button>
						</>
					}>
					<Row gutter={12}>
						<Col sm={{span: 18, offset: 3}}>
							<Steps current={1} labelPlacement="vertical">
								<Step title="下载模板、上传文件" />
								<Step title="数据检测、执行导入" />
								<Step title="确认结果、完成导入" />
							</Steps>
						</Col>
						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-xiazai" />
								</div>
								<div className="inlineText">
									<div className="text title">
										下载文件模板、填写导入信息
									</div>
									<div className="text ">
										必填字段：XX1字段、XX2字段、XX3字段
									</div>
									<div className="text">
										禁止重复：XX1字段
									</div>
									<>
										<Upload {...uploadProps}>
											<Button
												type="primary"
												shape="round"
												size="small"
												className="downOrupload">
												请选择文件
											</Button>
										</Upload>
									</>
								</div>
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-a-shangchuan1" />
								</div>
								<div className="inlineText">
									<div className="text title">
										下载文件模板、填写导入信息
									</div>
									<div className="text">
										必填字段：XX1字段、XX2字段、XX3字段
									</div>
									<div className="text">
										禁止重复：XX1字段
									</div>
									<>
										<Button
											type="primary"
											shape="round"
											size="small"
											className="downOrupload">
											请选择文件
										</Button>
									</>
								</div>
							</div>
						</Col>
					</Row>
				</Modal> */}
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				setFileObj={setFileObj}
				importData={importData}
				fileData={{type: 1}}
				onTableList={onTableList}
				fileNmae="excel"
				uploadFileUrl={`${modalApi.carMessage}/assetscarmaintenance/importMaintenance`}
				columns={batchColumns}
				sourceId={5}
				templateType="维保工单导入"
			/>
		</div>
	)
})
export default connect(({user}: any) => ({user}))(targetDom)
